<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="资产ID" prop="assetId">
        <el-input
          v-model="queryParams.assetId"
          placeholder="请输入资产ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="借用人" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入借用人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核人" prop="adminId">
        <el-input
          v-model="queryParams.adminId"
          placeholder="请输入审核人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核结果" prop="auditResult">
        <el-select v-model="queryParams.auditResult" placeholder="请选择审核结果" clearable>
          <el-option label="通过" value="1" />
          <el-option label="拒绝" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['assets:brlog:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="brlogList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="日志ID" align="center" prop="borrowLogId" />
      <el-table-column label="资产ID" align="center" prop="assetId" width="180" />
      <el-table-column label="借用人" align="center" prop="userId">
        <template slot-scope="scope">
          <span>{{ userMap[scope.row.userId] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="借用时间" align="center" prop="borrowTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.borrowTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="借用地点" align="center" prop="borrowLocation" width="120" />
      <el-table-column label="归还时间" align="center" prop="returnTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.returnTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="归还地点" align="center" prop="returnLocation" width="120" />
      <el-table-column label="审核人" align="center" prop="adminId">
        <template slot-scope="scope">
          <span>{{ userMap[scope.row.adminId] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核时间" align="center" prop="approveTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approveTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核结果" align="center">
        <template slot-scope="scope">
          <el-tag
            :type="getAuditResultType(scope.row.auditResult)"
            :style="{ backgroundColor: getAuditResultColor(scope.row.auditResult), color: 'white' }"
          >
            {{ getAuditResultText(scope.row.auditResult) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleTrack(scope.row)"
            v-hasPermi="['assets:brlog:track']"
          >使用轨迹</el-button>
          <!-- 其他按钮 -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改借还日志对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBrlog, getBrlog, delBrlog, addBrlog, updateBrlog } from "@/api/assets/brlog";
import {parseTime} from "@/utils/ruoyi";
import {listUser} from "@/api/system/user";


export default {
  name: "Brlog",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 借还日志表格数据
      brlogList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        assetId: null,
        userId: null,
        adminId: null,
        auditResult: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        assetId: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        borrowTime: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
        auditResult: [
          { required: true, message: "审核结果不能为空", trigger: "blur" }
        ],
      },
      // 定义 statusMap 对象
      statusMap: {
        '0': '拒绝',
        '1': '通过'
      },
      // 定义 statusColorMap 对象
      statusColorMap: {
        '0': 'red',
        '1': 'green'
      },
      // 用户信息缓存
      userMap: {}
    };
  },
  created() {
    this.getList();
    this.getUserList(); // 获取用户信息并缓存
  },
  methods: {
    parseTime,
    /** 查询借还日志列表 */
    getList() {
      this.loading = true;
      listBrlog(this.queryParams).then(response => {
        this.brlogList = response.rows.map(row => {
          row.auditResultText = this.statusMap[row.auditResult] || row.auditResult;
          return row;
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    getUserList() {
      listUser().then(response => {
        this.userMap = response.rows.reduce((map, user) => {
          map[user.userId] = user.userName;
          return map;
        }, {});
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        borrowLogId: null,
        assetId: null,
        userId: null,
        borrowTime: null,
        returnTime: null,
        borrowLatitude: null,
        borrowLongitude: null,
        borrowAltitude: null,
        returnLatitude: null,
        returnLongitude: null,
        returnAltitude: null,
        borrowLocation: null,
        returnLocation: null,
        borrowReason: null,
        adminId: null,
        approveTime: null,
        auditResult: null,
      };
      this.resetForm("form");
    },
    handleTrack(row) {
      this.$router.push({
        path: "/useTrack",
        query: {
          assetId: row.assetId,
          borrowLogId: row.borrowLogId
        }
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.borrowLogId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加借还日志";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const borrowLogId = row.borrowLogId || this.ids
      getBrlog(borrowLogId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改借还日志";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.borrowLogId != null) {
            updateBrlog(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBrlog(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const borrowLogIds = row.borrowLogId || this.ids;
      this.$modal.confirm('是否确认删除借还日志编号为"' + borrowLogIds + '"的数据项？').then(function() {
        return delBrlog(borrowLogIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('assets/brlog/export', {
        ...this.queryParams
      }, `brlog_${new Date().getTime()}.xlsx`)
    },
    // 新增 getAuditResultType 方法
    getAuditResultType(auditResult) {
      if (auditResult === 0) return 'danger'; // 拒绝
      if (auditResult === 1) return 'success'; // 通过
      return ''; // 默认返回空字符串
    },
    // 新增 getAuditResultColor 方法
    getAuditResultColor(auditResult) {
      if (auditResult === 0) return 'red'; // 拒绝
      if (auditResult === 1) return 'green'; // 通过
      return '#FFD700'; // 默认返回空字符串
    },
    // 新增 getAuditResultText 方法
    getAuditResultText(auditResult) {
      if (auditResult === 0) return '拒绝';
      if (auditResult === 1) return '通过';
      return '待审核'; // 默认返回空字符串
    }
  }
};
</script>
